package com.zhang.internalcommon.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhang.internalcommon.dto.TokenResult;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtils {
	private static final String SIGN = "ibelieveiwillsuccess@#!$@wwww";
	private static final String JWT_KEY_PHONE = "phone";
	private static final String JWT_KEY_IDENTITY = "identity";
	private static final String JWT_TOKEN_TYPE = "tokenType";
	private static final String JWT_TOKEN_TIME = "tokenTime";

	public static String generateToken(String passengerPhone, String identity, String tokenType) {
		Map<String, String> map = new HashMap<>();
		// map.put("passengerPhone", passengerPhone);
		map.put(JWT_KEY_PHONE, passengerPhone);
		map.put(JWT_KEY_IDENTITY, identity);
		map.put(JWT_TOKEN_TYPE, tokenType);
		// token过期时间
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, 1);
		Date date = calendar.getTime();
		map.put(JWT_TOKEN_TYPE, date.toString());
		JWTCreator.Builder builder = JWT.create();
		map.forEach(builder::withClaim);
		// 整合过期时间
		// builder.withExpiresAt(date);
		// 生成token
		String sign = builder.sign(Algorithm.HMAC256(SIGN));
		return sign;
	}

	public static TokenResult parseToken(String token) {
		DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
		String phone = verify.getClaim(JWT_KEY_PHONE).asString();
		String identity = verify.getClaim(JWT_KEY_IDENTITY).asString();

		TokenResult tokenResult = new TokenResult();
		tokenResult.setPhone(phone);
		tokenResult.setIdentity(identity);
		return tokenResult;
	}

	public static TokenResult checkToken(String token) {
		TokenResult tokenResult = null;
		try {
			tokenResult = JwtUtils.parseToken(token);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return tokenResult;
	}

	// public static void main(String[] args) {
	// 	// HashMap<String, String> map = new HashMap<>();
	// 	// map.put("name", "zhang");
	// 	// map.put("age", "18");
	// 	// String token = generateToken(map);
	// 	// System.out.println(token);
	// 	// String token = generateToken("155512148005");
	// 	// System.out.println(token);
	// 	// String phone = parseToken(token);
	// 	// System.out.println(phone);
	//
	// 	String token = generateToken("1155123123", "1");
	// 	System.out.println(token);
	// 	TokenResult tokenResult = parseToken(token);
	// 	System.out.println(tokenResult);
	// }
}
